<template>
  <div class="location-table">
    <!-- 搜索表单 -->
    <el-form :inline="true" :model="searchForm" class="demo-form-inline">
      <el-form-item label="名称">
        <el-input v-model="searchForm.name" placeholder="请输入地点名称"></el-input>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="searchForm.createTimeRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="yyyy-MM-dd HH:mm:ss"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="更新时间">
        <el-date-picker
          v-model="searchForm.updateTimeRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="yyyy-MM-dd HH:mm:ss"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table
      v-loading="loading"
      :data="paginatedLocations"
      style="width: 100%"
    > 
      <el-table-column prop="name" label="名称" />
      <el-table-column label="位置">
        <template #default="{ row }">
          {{ row.location.attitude }}, {{ row.location.latitude }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间">
        <template #default="{ row }">
          {{ row.createTime.startTime }}
        </template>
      </el-table-column>
      <el-table-column label="更新时间">
        <template #default="{ row }">
          {{ row.updateTime.startTime }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="{ row }">
          <el-button type="text" size="small" @click="handleDetail(row)">查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pageSize"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue';
import { locationApi } from '@/api/locations';
import { useRouter } from 'vue-router';

const router = useRouter();

const locations = ref([]); // 数据列表
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const searchForm = ref({
  name: '',
  attitude: '',
  latitude: '',
  createTimeRange: [],
  updateTimeRange: []
});

// 获取地点列表数据
const fetchData = async () => {
  loading.value = true;
  try {
    const response = await locationApi.getLocations();
    locations.value = Array.isArray(response.data) ? response.data : []; // 确保为数组
  } catch (error) {
    console.error('获取数据失败:', error);
  } finally {
    loading.value = false;
  }
};

const handleSearch = () => {
  currentPage.value = 1;
  fetchData();
};

const handleReset = () => {
  searchForm.value = {
    name: '',
    createTimeRange: [],
    updateTimeRange: []
  };
  currentPage.value = 1;
  fetchData();
};

const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchData();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchData();
};

const handleDetail = (row) => {
  router.push({ name: 'LocationDetail', params: { id: row.locationID } });
};

const filteredLocations = computed(() => {
  if (!Array.isArray(locations.value)) return []; // 确保是数组
  return locations.value.filter(item => {
    // 名称筛选
    if (searchForm.value.name &&
        !item.name.toLowerCase().includes(searchForm.value.name.toLowerCase())) {
      return false;
    }
    
    // 创建时间范围筛选
    if (searchForm.value.createTimeRange?.length === 2) {
      const createTime = new Date(item.createTime.startTime).getTime();
      const startTime = new Date(searchForm.value.createTimeRange[0]).getTime();
      const endTime = new Date(searchForm.value.createTimeRange[1]).getTime();
      if (createTime < startTime || createTime > endTime) {
        return false;
      }
    }
    
    // 更新时间范围筛选
    if (searchForm.value.updateTimeRange?.length === 2) {
      const updateTime = new Date(item.updateTime.startTime).getTime();
      const startTime = new Date(searchForm.value.updateTimeRange[0]).getTime();
      const endTime = new Date(searchForm.value.updateTimeRange[1]).getTime();
      if (updateTime < startTime || updateTime > endTime) {
        return false;
      }
    }
    
    return true;
  });
});

const paginatedLocations = computed(() => {
  // 使用过滤后的数据进行分页
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredLocations.value.slice(start, end);
});

watch(filteredLocations, (val) => {
  total.value = val.length;
  if (currentPage.value > Math.ceil(total.value / pageSize.value)) {
    currentPage.value = 1;
  }
}, { immediate: true });

onMounted(() => {
  console.log('onMounted triggered');
  fetchData();
});
</script>

<style scoped>
.location-table {
  padding: 20px;
}
</style>
